import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
import router from "@/router";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 基础地址
  timeout: 10000,
}); // 创建一个新的axios实例
// 成功1 失败2
service.interceptors.request.use(
  (config) => {
    // 注入token
    //  this.$store.getters
    // store.getters.token => 请求头里面
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`;
    }
    return config;
  },
  (error) => {
    // 失败执行promise
    console.log("这里是20");
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // axios默认包裹了data
    const { data, msg, code } = response.data;
    if (code === "00000") {
      return data;
    } else {
      Message({
        message: msg,
        type: "error",
      });
      return Promise.reject(new Error(msg));
    }
  },
  async (error) => {
    // error.message
    // token超时
    if (error.response.status === 401) {
      await store.dispatch("user/logout"); //退出登录
      router.push("/login");
      Message({
        message: "token验证过期",
        type: "warning",
      });
    } else if (error.response.status === 400) {
      Message({
        message: "用户名或密码错误",
        type:'error'
      });
    }
    return Promise.reject(error);
  }
);

export default service;
